<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Common\Tree;
//哪个控制器需要权限控制就加上权限继承
class CategoryController extends Controller {
	// public static $id;
    public  function index(){

    	$link =M('category');
    	$categorys = $link->select();//查询数据库
    	// var_dump($categorys);
    	$obj = new Tree();
    	$categorys =$obj->reload($categorys);//将查询出来的数据遍历然后输出到模板
    	// var_dump($categorys);
    	$this->assign('categorys',$categorys);


        $this->display();
    }

//*********************添加分类
    public function add(){
    	if ($_POST) {
    		// var_dump($_POST);exit;
	    	$data['fid']=I('post.fid',0);// 如果不存在$_POST['fid'] 则返回0
	    	$data['cname']=I('post.cname');

			$link =M('category');
	    	$res = $link->add($data);//插入数据
	    	if ($res) {
	    		$this->success('添加成功',U('Admin/Category/index'));
	    	}else{
	    		$this->error('添加失败',U('Admin/Category/index'));
	    	}
		}else{
			$this->error('非法请求',U('Admin/Category/index'));
		}
 	}


 	public function del(){
 		if ($_GET) {

	 		$link =M('category');
	
	 		$sql ="delete from category where id ={$_GET['url']} ";

	 		$data =$link->execute($sql);
	 		// var_dump($data);
	 		$this->success('删除成功!');
 		}else{
 			$this->error('删除失败!');
 		}
 		
 	}


 	public function edit(){
 		
 			//把数据输出到编辑模板
	 		$link =M('category');
	    	$categorys = $link->select();//查询数据库
	    	// var_dump($categorys);
	    	$obj = new Tree();
	    	$categorys =$obj->reload($categorys);//将查询出来的数据遍历然后输出到模板
	    	// var_dump($categorys);
	    	$this->assign('categorys',$categorys);

	    if ($_GET) {
	    	// var_dump($_GET);
	    	$sql ="select * from category where id ={$_GET['url']} ";//抓到需要修改的项的id
	    	$data =current($link->query($sql));
	    	// var_dump($data);
	    	$this->assign('data',$data);//把需要修改的项的数据分配到模板
	    	
			$_SESSION['fid'] = $_GET['url'];//把Get抓到的id存到SESSION 传给post用

 		}
 		
 		
    	
		if ($_POST) {
    		
    		$fid =I('post.id');
    		$cname=I('post.class-val');
    		// var_dump($_SESSION['fid'],$fid,$cname);
    		$sql ="update category set fid='{$fid}',cname='{$cname}' where id ={$_SESSION['fid']}";
    		// var_dump($sql);
    		$link->execute($sql);
    		$this->success('修改成功!',U('Admin/Category/index'));
    		
    		// $date =current($link->execute($sql));
    		
    	}else{
    		$this->display('edit');
    	}


 		
 	}


}